/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package FamousBallet;

import com.sun.glass.events.KeyEvent;
import java.awt.Color;
import java.awt.Toolkit;
import javax.swing.JOptionPane;

/**
 *<pre>
 File name  Edit.java
 * @author    <b><i>Yerong</i></b>
 * Instructor  Niko Culevski
 * Class       CS 141 B
 * Due date    11/29/2016
 * Assignment  Project_3
 * @version   1.0.1
 * @see       com.sun.glass.events.KeyEvent
 * @see       java.awt.Toolkit
 * @see       javax.swing.JOptionPane
 * @see       javax.swing.JDialog
 * Platform    PC, Windows 10, NetBeans 8.1
 *******************************************************************************
* This is the edit and add form of the FamousBallet program.
* Users can edit or add the ballet in this form.
* This form also checks whether the input is valid by Validation class.
 *******************************************************************************
 * Input:    An existed Ballet object or nothing
 * Output:   The new ballet object
 *******************************************************************************
 * </pre>
 */
public class Edit extends javax.swing.JDialog {

    /**
     * Creates new form Manage
     */
    
    //Variables for returning object.
    String name, composer, city, synopsis, link;
    int year;
    
    //Boolean variable for checking what does the form for(Edit/New).
    boolean edit = true; 
    
    //Temp Ballet for editing.
    Ballet tempBallet = new Ballet();
    
    //Default constructor
    public Edit(java.awt.Frame parent, boolean modal) {
        super(parent, modal);
        initComponents();
    }
    
    //Overloaded constructor, used to check adding or editing
    public Edit(java.awt.Frame parent, boolean modal, boolean check) {
    super(parent, modal);
    initComponents();
    //Set the form in the center of the screen
    this.setLocationRelativeTo(null);
    //Set the Calculate button as default. It fires when you press "Enter."
    this.getRootPane().setDefaultButton(saveJButton);
    //Set icon
    this.setIconImage(
    Toolkit.getDefaultToolkit().getImage("src/FamousBallet/Bunny.png"));
    
    //Check whether it is editing or adding.
    this.edit = check;
    
    //Change the title by check value
    if(edit==true){
        this.setTitle("Edit the Ballet");
        titleJLabel.setText("Edit the Ballet");
    }
    else{
        this.setTitle("Add a new Ballet");
        titleJLabel.setText("Add a new Ballet");
        }
    }

    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method loadBallet()
     * Load the selected ballet to the edit class.
     * @param ballet the selected ballet
     * @author Yerong
     * Date: 11/29/2016
     */     
    public void loadBallet(Ballet ballet){
        //Load the ballet
        this.tempBallet = ballet;
        
        //Load the information
        nameJTextField.setText(tempBallet.getName());
        cityJTextField.setText(tempBallet.getCity());
        composerJTextField.setText(tempBallet.getComposer());
        yearJTextField.setText(String.valueOf(tempBallet.getYear()));
        synopsisJTextArea.setText(tempBallet.getSynopsis());
        //Set the caret postition to 0
        synopsisJTextArea.setCaretPosition(0);
        linkJTextField.setText(tempBallet.getLink());
        //Set the caret postition to 0
        linkJTextField.setCaretPosition(0);
    }
    
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method getBallet()
     * Return the tempBallet to the famousGUI.
     * @return tempBallet
     * @author Yerong
     * Date: 11/29/2016
     */         
    public Ballet getBallet(){
        return tempBallet;
    }

    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        titleJLabel = new javax.swing.JLabel();
        dataJPanel = new javax.swing.JPanel();
        nameJLabel = new javax.swing.JLabel();
        nameJTextField = new javax.swing.JTextField();
        composerJLabel = new javax.swing.JLabel();
        composerJTextField = new javax.swing.JTextField();
        yearJLabel = new javax.swing.JLabel();
        yearJTextField = new javax.swing.JTextField();
        cityJLabel = new javax.swing.JLabel();
        cityJTextField = new javax.swing.JTextField();
        synopsisJLabel = new javax.swing.JLabel();
        synopsisJScrollPane = new javax.swing.JScrollPane();
        synopsisJTextArea = new javax.swing.JTextArea();
        linkJLabel = new javax.swing.JLabel();
        linkJTextField = new javax.swing.JTextField();
        operateJPanel = new javax.swing.JPanel();
        saveJButton = new javax.swing.JButton();
        exitJButton = new javax.swing.JButton();

        setDefaultCloseOperation(javax.swing.WindowConstants.DISPOSE_ON_CLOSE);
        setMaximumSize(new java.awt.Dimension(500, 430));
        setMinimumSize(new java.awt.Dimension(500, 430));
        setPreferredSize(new java.awt.Dimension(500, 430));
        setResizable(false);

        titleJLabel.setBackground(new java.awt.Color(204, 204, 204));
        titleJLabel.setFont(new java.awt.Font("Times New Roman", 0, 24)); // NOI18N
        titleJLabel.setHorizontalAlignment(javax.swing.SwingConstants.CENTER);
        titleJLabel.setText("Edit");
        getContentPane().add(titleJLabel, java.awt.BorderLayout.NORTH);

        dataJPanel.setLayout(new java.awt.GridLayout(6, 2, 0, 5));

        nameJLabel.setBackground(new java.awt.Color(204, 204, 204));
        nameJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        nameJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        nameJLabel.setText("Name:");
        dataJPanel.add(nameJLabel);

        nameJTextField.setBackground(new java.awt.Color(204, 204, 204));
        nameJTextField.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        nameJTextField.setToolTipText("A valid ballet name should contains one or two words begin with an upper case letter");
        dataJPanel.add(nameJTextField);

        composerJLabel.setBackground(new java.awt.Color(204, 204, 204));
        composerJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        composerJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        composerJLabel.setText("Composer:");
        dataJPanel.add(composerJLabel);

        composerJTextField.setBackground(new java.awt.Color(204, 204, 204));
        composerJTextField.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        composerJTextField.setToolTipText("A valid composer name should contains two or three words begin with an upper case letter.");
        dataJPanel.add(composerJTextField);

        yearJLabel.setBackground(new java.awt.Color(204, 204, 204));
        yearJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        yearJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        yearJLabel.setText("Year first performed:");
        dataJPanel.add(yearJLabel);

        yearJTextField.setBackground(new java.awt.Color(204, 204, 204));
        yearJTextField.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        yearJTextField.setToolTipText("Year should contain 4 numbers.");
        yearJTextField.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                yearJTextFieldActionPerformed(evt);
            }
        });
        yearJTextField.addKeyListener(new java.awt.event.KeyAdapter() {
            public void keyTyped(java.awt.event.KeyEvent evt) {
                yearJTextFieldKeyTyped(evt);
            }
        });
        dataJPanel.add(yearJTextField);

        cityJLabel.setBackground(new java.awt.Color(204, 204, 204));
        cityJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        cityJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        cityJLabel.setText("City first performed:");
        dataJPanel.add(cityJLabel);

        cityJTextField.setBackground(new java.awt.Color(204, 204, 204));
        cityJTextField.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        cityJTextField.setToolTipText("A city name should contains one word begin with an upper case letter.");
        dataJPanel.add(cityJTextField);

        synopsisJLabel.setBackground(new java.awt.Color(204, 204, 204));
        synopsisJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        synopsisJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        synopsisJLabel.setText("Synopsis:");
        dataJPanel.add(synopsisJLabel);

        synopsisJTextArea.setBackground(new java.awt.Color(204, 204, 204));
        synopsisJTextArea.setColumns(50);
        synopsisJTextArea.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        synopsisJTextArea.setLineWrap(true);
        synopsisJTextArea.setRows(5);
        synopsisJTextArea.setToolTipText("Synopsis should begin with an upper letter and contain several \"space and number or characters.\"");
        synopsisJScrollPane.setViewportView(synopsisJTextArea);

        dataJPanel.add(synopsisJScrollPane);

        linkJLabel.setBackground(new java.awt.Color(204, 204, 204));
        linkJLabel.setFont(new java.awt.Font("Times New Roman", 0, 14)); // NOI18N
        linkJLabel.setHorizontalAlignment(javax.swing.SwingConstants.LEFT);
        linkJLabel.setText("Link to Youtube:");
        dataJPanel.add(linkJLabel);

        linkJTextField.setBackground(new java.awt.Color(204, 204, 204));
        linkJTextField.setFont(new java.awt.Font("Times New Roman", 0, 12)); // NOI18N
        linkJTextField.setToolTipText("Input the valid link.");
        dataJPanel.add(linkJTextField);

        getContentPane().add(dataJPanel, java.awt.BorderLayout.CENTER);

        operateJPanel.setMinimumSize(new java.awt.Dimension(172, 35));
        operateJPanel.setLayout(new java.awt.GridLayout(1, 2, 50, 0));

        saveJButton.setMnemonic('S');
        saveJButton.setText("Save");
        saveJButton.setToolTipText("Save the data");
        saveJButton.setPreferredSize(new java.awt.Dimension(61, 35));
        saveJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                saveJButtonActionPerformed(evt);
            }
        });
        operateJPanel.add(saveJButton);

        exitJButton.setMnemonic('C');
        exitJButton.setText("Cancel");
        exitJButton.setToolTipText("Close the form");
        exitJButton.setPreferredSize(new java.awt.Dimension(61, 35));
        exitJButton.addActionListener(new java.awt.event.ActionListener() {
            public void actionPerformed(java.awt.event.ActionEvent evt) {
                exitJButtonActionPerformed(evt);
            }
        });
        operateJPanel.add(exitJButton);

        getContentPane().add(operateJPanel, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents

    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method exitJButtonActionPerformed()
     * Dispose the form and set tempBallet null
     * @return null
     * @param evt, the event
     * @see java.awt.event.ActionEvent
     * @author Yerong
     * Date: 11/29/2016
     */      
    private void exitJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_exitJButtonActionPerformed
        tempBallet = null;
        this.dispose();
    }//GEN-LAST:event_exitJButtonActionPerformed

    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method loadInformation()
     * Set all the attributions of tempBallet to the user inputs.
     * @return null
     * @author Yerong
     * Date: 11/29/2016
     */      
    private void loadInformation(){
        tempBallet.setName(nameJTextField.getText());
        tempBallet.setCity(cityJTextField.getText());
        tempBallet.setComposer(composerJTextField.getText());
        tempBallet.setSynopsis(synopsisJTextArea.getText());
        tempBallet.setYear(Integer.valueOf(yearJTextField.getText()));
        tempBallet.setLink(linkJTextField.getText());    
    }
    
    /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method validateInfo()
     * Validate the user inputs, and if any one of the inputs is wrong,
     * highlight the JTextField.
     * @return null
     * @author Yerong
     * Date: 11/29/2016
     */     
    public boolean validateInfo(){
        boolean validate = true;
        //If any input is wrong, show message.
        if(!Validation.isValidBalletName(nameJTextField.getText())){
            nameJTextField.setBackground(Color.red);    
            validate = false;
        }else nameJTextField.setBackground(Color.white);
        if(!Validation.isValidName(composerJTextField.getText())){
            composerJTextField.setBackground(Color.red);
            validate = false;
        }else composerJTextField.setBackground(Color.white);
        if(!Validation.isValidCity(cityJTextField.getText())){
            cityJTextField.setBackground(Color.red);
            validate = false;
        }else cityJTextField.setBackground(Color.white);
        if(!Validation.isValidLink(linkJTextField.getText())){
            linkJTextField.setBackground(Color.red);
            validate = false;
        }else linkJTextField.setBackground(Color.white);
        if(!Validation.isValidYear(yearJTextField.getText())||
                Integer.parseInt(yearJTextField.getText())>2015){
            yearJTextField.setBackground(Color.red);
            validate = false;
        }else yearJTextField.setBackground(Color.white);
        if(!Validation.isValidSentences(synopsisJTextArea.getText())){
            synopsisJTextArea.setBackground(Color.red);
            validate = false;
        }else synopsisJTextArea.setBackground(Color.white);
        
        return validate;
    }
    
     /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method saveJButtonActionPerformed()
     * Try to load the information to the tempBallet and dispose the
     * form.
     * @param evt,the event
     * @see java.awt.event.ActionEvent
     * @return null
     * @author Yerong
     * Date: 11/29/2016
     */       
    private void saveJButtonActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_saveJButtonActionPerformed
        try{
                if(validateInfo()){
                    loadInformation();
                    this.dispose();}
            }catch(NumberFormatException numexp){
                JOptionPane.showMessageDialog(null, 
                        "Please fullfill the information, and the year should"+
                                " be 4-digi numbers!","Empty Information",
                        JOptionPane.ERROR_MESSAGE);
            }
    }//GEN-LAST:event_saveJButtonActionPerformed

     /**~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
     * Method yearJTextFieldKeyTyped()
     * Doesn't allow the user type other than numbers, backspace, dele-
     * -te and enter keys, and the maximum length are limited to 4 nums
     * @param evt,the event
     * @see java.awt.event.ActionEvent
     * @return null
     * @author Yerong
     * Date: 11/29/2016
     */      
    private void yearJTextFieldKeyTyped(java.awt.event.KeyEvent evt) {//GEN-FIRST:event_yearJTextFieldKeyTyped
        // Declear the maximum length of the number
        final byte MAX_LENGTH = 4;
        
        //Get the char
        char charTyped = evt.getKeyChar();
        
        //Detect whether the number is valid, if not, beep() and consume().
        if(!((Character.isDigit(charTyped)) ||
                (charTyped == KeyEvent.VK_BACKSPACE) ||
                (charTyped == KeyEvent.VK_DELETE) ||
                (charTyped == KeyEvent.VK_ENTER)) ||
                (yearJTextField.getText().length() >= MAX_LENGTH)){
          getToolkit().beep();
          evt.consume();
        }
    }//GEN-LAST:event_yearJTextFieldKeyTyped

    private void yearJTextFieldActionPerformed(java.awt.event.ActionEvent evt) {//GEN-FIRST:event_yearJTextFieldActionPerformed

    }//GEN-LAST:event_yearJTextFieldActionPerformed

    /**
     * @param args the command line arguments
     */
    public static void main(String args[]) {
        /* Set the Nimbus look and feel */
        //<editor-fold defaultstate="collapsed" desc=" Look and feel setting code (optional) ">
        /* If Nimbus (introduced in Java SE 6) is not available, stay with the default look and feel.
         * For details see http://download.oracle.com/javase/tutorial/uiswing/lookandfeel/plaf.html 
         */
        try {
            for (javax.swing.UIManager.LookAndFeelInfo info : javax.swing.UIManager.getInstalledLookAndFeels()) {
                if ("Nimbus".equals(info.getName())) {
                    javax.swing.UIManager.setLookAndFeel(info.getClassName());
                    break;
                }
            }
        } catch (ClassNotFoundException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (InstantiationException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (IllegalAccessException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        } catch (javax.swing.UnsupportedLookAndFeelException ex) {
            java.util.logging.Logger.getLogger(Edit.class.getName()).log(java.util.logging.Level.SEVERE, null, ex);
        }
        //</editor-fold>
        //</editor-fold>

        /* Create and display the dialog */
        java.awt.EventQueue.invokeLater(new Runnable() {
            public void run() {
                Edit dialog = new Edit(new javax.swing.JFrame(), true);
                dialog.addWindowListener(new java.awt.event.WindowAdapter() {
                    @Override
                    public void windowClosing(java.awt.event.WindowEvent e) {
                        System.exit(0);
                    }
                });
                dialog.setVisible(true);
            }
        });
    }

    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JLabel cityJLabel;
    private javax.swing.JTextField cityJTextField;
    private javax.swing.JLabel composerJLabel;
    private javax.swing.JTextField composerJTextField;
    private javax.swing.JPanel dataJPanel;
    private javax.swing.JButton exitJButton;
    private javax.swing.JLabel linkJLabel;
    private javax.swing.JTextField linkJTextField;
    private javax.swing.JLabel nameJLabel;
    private javax.swing.JTextField nameJTextField;
    private javax.swing.JPanel operateJPanel;
    private javax.swing.JButton saveJButton;
    private javax.swing.JLabel synopsisJLabel;
    private javax.swing.JScrollPane synopsisJScrollPane;
    private javax.swing.JTextArea synopsisJTextArea;
    private javax.swing.JLabel titleJLabel;
    private javax.swing.JLabel yearJLabel;
    private javax.swing.JTextField yearJTextField;
    // End of variables declaration//GEN-END:variables
}
